package com.example.administrator.activity.music;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;

import java.io.IOException;

public class MusicService extends Service {
    MediaPlayer mediaPlayer;
    //    接受intent传递过来的值
    int state;
    String path;
    Intent intent;

    public MusicService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mediaPlayer = new MediaPlayer();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        /**
         * 接受intent传递的值，根据状态决定要执行什么功能
         */
        state = intent.getIntExtra("state", 0);
        path=intent.getStringExtra("path");
        switch (state) {
            case 1:

                try {
                    mediaPlayer.reset();
                    mediaPlayer.setDataSource(path);
                    mediaPlayer.prepare();
                    mediaPlayer.start();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                break;
            case 2:
                mediaPlayer.pause();
                break;
            case 3:
                mediaPlayer.start();
                break;
            case 4:
                mediaPlayer.stop();
                break;
            default:
                break;

        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mediaPlayer!=null){
            mediaPlayer.release();
            mediaPlayer=null;

        }
    }
}
